// 企业信息数据存储服务

class CompanyStore {
  constructor() {
    // 初始化企业人物数据
    this.companyPeople = JSON.parse(localStorage.getItem('companyPeople')) || [];
    // 初始化企业发展历程数据
    this.companyMilestones = JSON.parse(localStorage.getItem('companyMilestones')) || [];
    this.listeners = [];
    this.isLoading = false;
  }

  // 添加数据变化监听器
  addListener(listener) {
    if (!this.listeners.includes(listener)) {
      this.listeners.push(listener);
    }
  }

  // 移除数据变化监听器
  removeListener(listener) {
    this.listeners = this.listeners.filter(l => l !== listener);
  }

  // 通知所有监听器数据已更新
  notifyListeners() {
    this.listeners.forEach(listener => {
      try {
        listener();
      } catch (error) {
        console.error('Error in listener:', error);
      }
    });
  }

  // 保存企业人物数据到本地存储
  savePeopleToLocalStorage() {
    localStorage.setItem('companyPeople', JSON.stringify(this.companyPeople));
    this.notifyListeners();
  }

  // 保存企业发展历程数据到本地存储
  saveMilestonesToLocalStorage() {
    localStorage.setItem('companyMilestones', JSON.stringify(this.companyMilestones));
    this.notifyListeners();
  }

  // ====================== 企业人物管理 ======================
  
  // 获取所有企业人物
  getAllCompanyPeople() {
    // 按创建时间排序，最新的在前面
    return [...this.companyPeople].sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
  }

  // 根据ID获取企业人物
  getCompanyPersonById(id) {
    return this.companyPeople.find(person => person.id === id);
  }

  // 添加新的企业人物
  addCompanyPerson(personData) {
    try {
      const newPerson = {
        id: Date.now().toString(),
        ...personData,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      };
      this.companyPeople.push(newPerson);
      this.savePeopleToLocalStorage();
      return newPerson;
    } catch (error) {
      console.error('Failed to add company person:', error);
      return null;
    }
  }

  // 更新企业人物
  updateCompanyPerson(id, personData) {
    try {
      const index = this.companyPeople.findIndex(person => person.id === id);
      if (index !== -1) {
        this.companyPeople[index] = {
          ...this.companyPeople[index],
          ...personData,
          updatedAt: new Date().toISOString()
        };
        this.savePeopleToLocalStorage();
        return this.companyPeople[index];
      }
      return null;
    } catch (error) {
      console.error('Failed to update company person:', error);
      return null;
    }
  }

  // 删除企业人物
  deleteCompanyPerson(id) {
    try {
      const initialLength = this.companyPeople.length;
      this.companyPeople = this.companyPeople.filter(person => person.id !== id);
      
      if (this.companyPeople.length !== initialLength) {
        this.savePeopleToLocalStorage();
        return true;
      }
      return false;
    } catch (error) {
      console.error('Failed to delete company person:', error);
      return false;
    }
  }

  // ====================== 企业发展历程管理 ======================
  
  // 获取所有企业发展历程
  getAllMilestones() {
    // 按时间排序（从早到晚）
    return [...this.companyMilestones].sort((a, b) => new Date(a.year) - new Date(b.year));
  }

  // 根据ID获取企业发展历程
  getMilestoneById(id) {
    return this.companyMilestones.find(milestone => milestone.id === id);
  }

  // 添加新的企业发展历程
  addMilestone(milestoneData) {
    try {
      const newMilestone = {
        id: Date.now().toString(),
        ...milestoneData,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      };
      this.companyMilestones.push(newMilestone);
      this.saveMilestonesToLocalStorage();
      return newMilestone;
    } catch (error) {
      console.error('Failed to add milestone:', error);
      return null;
    }
  }

  // 更新企业发展历程
  updateMilestone(id, milestoneData) {
    try {
      const index = this.companyMilestones.findIndex(milestone => milestone.id === id);
      if (index !== -1) {
        this.companyMilestones[index] = {
          ...this.companyMilestones[index],
          ...milestoneData,
          updatedAt: new Date().toISOString()
        };
        this.saveMilestonesToLocalStorage();
        return this.companyMilestones[index];
      }
      return null;
    } catch (error) {
      console.error('Failed to update milestone:', error);
      return null;
    }
  }

  // 删除企业发展历程
  deleteMilestone(id) {
    try {
      const initialLength = this.companyMilestones.length;
      this.companyMilestones = this.companyMilestones.filter(milestone => milestone.id !== id);
      
      if (this.companyMilestones.length !== initialLength) {
        this.saveMilestonesToLocalStorage();
        return true;
      }
      return false;
    } catch (error) {
      console.error('Failed to delete milestone:', error);
      return false;
    }
  }

  // 上传图片文件
  async uploadImage(file) {
    try {
      // 在实际项目中，这里应该调用后端API上传图片
      // 这里使用Base64编码模拟图片上传
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (e) => {
          resolve(e.target.result);
        };
        reader.onerror = () => {
          reject(new Error('图片上传失败'));
        };
        reader.readAsDataURL(file);
      });
    } catch (error) {
      console.error('Failed to upload image:', error);
      throw error;
    }
  }
}

// 导出单例
const store = new CompanyStore();
export default store;